package com.yazi.mxz.person.controller.shop;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;






import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.common.tool.PageLink;
import com.myframework.smhj.hibernate.Page;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.Sort;
import com.myframework.smhj.jackson.result.PageResult;
import com.myframework.smhj.jackson.result.ObjectResult;
import com.myframework.smhj.jackson.result.StatusResult;
import com.yazi.mxz.common.ComSetting;
import com.yazi.mxz.common.entity.beans.Goods;
import com.yazi.mxz.common.entity.beans.Store;
import com.yazi.mxz.common.entity.beans.StoreGoods;
import com.yazi.mxz.common.entity.beans.StoreGoodsPic;
import com.yazi.mxz.common.entity.enums.SettingId;
import com.yazi.mxz.common.entity.enums.StoreGoodsStatus;
import com.yazi.mxz.common.service.GoodsService;
import com.yazi.mxz.common.service.StoreGoodsService;
import com.yazi.mxz.person.controller.MyPageLink;
import com.yazi.mxz.person.data.form.shop.StoreGoodsForm;
import com.yazi.mxz.person.jackson.filter.StoreGoodsFilter;

@Controller("shop-storeGoodsController")
@RequestMapping("/shop/storeGoods")
public class StoreGoodsController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(StoreGoodsController.class);
	
	@Resource
	StoreGoodsService storeGoodsService;
	@Resource 
	GoodsService goodsService;
	
	@RequestMapping("/list")
	public String list(StoreGoods storeGoods, Searching si, Model model) {
		debug(log, "进入店铺商品列表页面");
		Long companyId;
		Page<StoreGoods> page;
		PageLink pl;

		try {
			companyId = getCompanyId();
			
			// 默认按修改排序字段倒序
			if (null == si.getSorts()) {
				List<Sort> sorts = new ArrayList<Sort>();
				sorts.add(new Sort("sort", true));
				si.setSorts(sorts);
			}
			
			// 只查当前店铺商品信息
			Store store = new Store();
			store.setStoreId(getStoreId());
			storeGoods.setStore(store);
			
			page = storeGoodsService.list(storeGoods, si);
			pl = new MyPageLink(page.getPaging());

		} catch (Exception e) {
			error(log, e, "进入店铺商品列表页面异常");
			model.addAttribute(TIP_MSG, e.getMessage());
			return FORWARD_TIP;
		}
		
		model.addAttribute("list", page.getList());
		model.addAttribute("pl", pl);
		model.addAttribute("companyId", companyId);
		model.addAttribute("statuses", StoreGoodsStatus.values());
		model.addAttribute("storeGoods", storeGoods);
		model.addAttribute("searchWord", si.getSearchWord());
		return "shop/storeGoods_list";
	}
	
	@RequestMapping("/add")
	public String add(Goods goods, Searching si, Model model) {
		debug(log, "进入商品添加页面");
		Page<Goods> page;
		PageLink pl;
		Long companyId;
		try {
			companyId = getCompanyId();
			page = goodsService.listForAddByStoreId(getStoreId(), goods, si);
			pl = new MyPageLink(page.getPaging());
		} catch (Exception e) {
			error(log, e, "进入商品添加页面异常");
			model.addAttribute(TIP_MSG, e.getMessage());
			return FORWARD_TIP;
		}
		model.addAttribute("list", page.getList());
		model.addAttribute("pl", pl);
		model.addAttribute("companyId", companyId);
		model.addAttribute("goods", goods);
		model.addAttribute("searchWord", si.getSearchWord());
		
		return "shop/storeGoods_add";
	}
	
	@RequestMapping("/addDo/json")
	@ResponseBody
	public StatusResult addDoJson(long[] goodsIds) {
		debug(log, "商品入库");
		StatusResult jsonResult = new StatusResult();
		try {
			storeGoodsService.addByStore(getStore(true), goodsIds);
			jsonResult.setOk();
		} catch (MyException e) {
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			error(log, e, "商品入库异常");
			jsonResult.setErrorMessage("入库失败，请联系管理员!");
		}
		return jsonResult;
	}
	
	@RequestMapping("/addAllDo/json")
	@ResponseBody
	public ObjectResult<?> addAllDoJson() {
		debug(log, "一键入库");
		ObjectResult<Integer> jsonResult = new ObjectResult<Integer>();
		Searching si = new Searching();
		si.setPageSize(Searching.MAX_PAGE_SIZE);
		Page<Goods> page;
		List<Goods> list;
		try {
			page = goodsService.listForAddByStoreId(getStoreId(), null, si);
			list = page.getList();
			for (Goods goods : list) {
				storeGoodsService.addForStore(getStoreId(), goods);
			}
			jsonResult.setResult(list.size());
			jsonResult.setOk();
		} catch (Exception e) {
			error(log, e, "商品一键入库异常");
			jsonResult.setErrorMessage("入库失败，请联系管理员!");
		}
		return jsonResult;
	}
	
	@RequestMapping("/edit")
	public String edit(long storeGoodsId, Model model) {
		debug(log, "进入店铺商品编辑页面");
		StoreGoods sg = storeGoodsService.one(storeGoodsId);
		if (null == sg || !sg.getStore().equals(getStore(true)) ) {
			return REDIRECT_INDEX;
		}
		StoreGoodsStatus[] status = StoreGoodsStatus.values();
		model.addAttribute("storeGoods", sg);
		model.addAttribute("status", status);
		model.addAttribute("picAmount", ComSetting.getInteger(SettingId.GOODS_PIC_AMOUNT));
		model.addAttribute("companyId", getCompanyId());
		return "shop/storeGoods_edit";
	}
	
	@RequestMapping("/editDo/json")
	@ResponseBody
	public StatusResult editDoJson(@Validated(StoreGoodsForm.Edit.class) StoreGoodsForm form, String[] pics) {
		StoreGoods storeGoods = form.get();
		debug(log, "保存店铺商品信息 ");
		StatusResult jsonResult = new StatusResult();
		
		try{
			
			// 图片
			if (null != pics) {
				
				int amount = ComSetting.getInteger(SettingId.GOODS_PIC_AMOUNT);
				if (pics.length > amount) {
					jsonResult.setFailMessage("图片超过限定数量：" + amount);
					return jsonResult;
				}
				
				Set<StoreGoodsPic> set = storeGoods.getStoreGoodsPics();
				for (String pic : pics) {
					StoreGoodsPic storeGoodsPic = new StoreGoodsPic();
					storeGoodsPic.setPic(pic);
					set.add(storeGoodsPic);
				}
			}
			
			storeGoodsService.editByStore(getStore(true), storeGoods);
			jsonResult.setOk();
		} catch (MyException e) {
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			error(log, e, "保存店铺商品信息异常");
			jsonResult.setErrorMessage("保存失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/stockConvertDo/json")
	@ResponseBody
	public StatusResult stockConvertDoJson(long storeGoodsId, float stockConvert) {
		debug(log, "保存折算库存");
		StatusResult jsonResult = new StatusResult();
		
		try{
			
			storeGoodsService.editStockConvertByStore(getStore(true), storeGoodsId, stockConvert);
			jsonResult.setOk();
		} catch (MyException e) {
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			error(log, e, "保存折算库存异常");
			jsonResult.setErrorMessage("保存失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/statusDo/json")
	@ResponseBody
	public StatusResult statusDoJson(long[] storeGoodsIds, StoreGoodsStatus status) {
		debug(log, "商品批量上下架");
		StatusResult jsonResult = new StatusResult();
		
		try{
			
			storeGoodsService.editStatusByStore(getStore(true), storeGoodsIds, status);
			jsonResult.setOk();
		} catch (MyException e) {
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			error(log, e, "商品批量上下架异常");
			jsonResult.setErrorMessage("保存失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/list/json")
	@ResponseBody
	public PageResult<?> listJson(StoreGoods storeGoods, Searching si) {
		debug(log, "搜索店铺商品 ");
		PageResult<StoreGoods> jsonResult = new PageResult<StoreGoods>();
		jsonResult.setFilter(StoreGoodsFilter.get());
		try {
			// 只能查找当前店铺商品
			Store store = new Store();
			store.setStoreId(getStoreId());
			storeGoods.setStore(store);
			
			Page<StoreGoods> page = storeGoodsService.list(storeGoods, si);
			jsonResult.setResult(page);
			jsonResult.setOk();
		} catch (Exception e) {
			error(log, e, "搜索店铺商品异常");
			jsonResult.setErrorMessage("查找失败,请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/list4Sync/json")
	@ResponseBody
	public PageResult<?> list4SyncJson(long updateTime, Searching si) {
		debug(log, "搜索店铺商品同步到本地 ");
		PageResult<StoreGoods> jsonResult = new PageResult<StoreGoods>();
		jsonResult.setFilter(StoreGoodsFilter.get());
		StoreGoods storeGoods4s = new StoreGoods();
		Store store = new Store();
		Page<StoreGoods> page;
		try {
			// 只能查找当前店铺商品
			store.setStoreId(getStoreId());
			storeGoods4s.setStore(store);
			storeGoods4s.setUpdateTime(updateTime);
			
			page = storeGoodsService.listByGtUpdateTime(storeGoods4s, si);
			jsonResult.setResult(page);
			jsonResult.setOk();
		} catch (Exception e) {
			error(log, e, "搜索店铺商品同步到本地异常");
			jsonResult.setErrorMessage("查找失败,请联系管理员");
		}
		return jsonResult;
	}
	
	/**
	 * 设置店铺商品置顶/沉底
	 * @param storeGoodsId
	 * @param sortType 排序类型：0沉底，1置顶
	 * @return
	 */
	@RequestMapping("/sortDo/json")
	@ResponseBody
	public StatusResult sortDo(long storeGoodsId, int sortType) {
		debug(log, "店铺商品排序");
		StatusResult jsonResult = new StatusResult();
		try {
			StoreGoods storeGoods = new StoreGoods();
			storeGoods.setStoreGoodsId(storeGoodsId);
			// 值越大越排前
			storeGoods.setSort(sortType == 1?DateUtil.getTimeStamp():0);
			storeGoodsService.editByStore(getStore(true), storeGoods);
			jsonResult.setOkMessage("设置成功");
		} catch (MyException e) {
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e ) {
			error(log, e, "店铺商品排序异常");
			jsonResult.setErrorMessage("设置失败，请刷新后重试");
		}
		return jsonResult;
	}
	

	@RequestMapping("/code/json")
	@ResponseBody
	public PageResult<?> codeJson(String barCode) {
		debug(log, "按编码查找商品");
		PageResult<StoreGoods> jsonResult = new PageResult<StoreGoods>();
		jsonResult.setFilter(StoreGoodsFilter.get());
		Page<StoreGoods> page;
		try {
			StoreGoods sg = new StoreGoods();
			sg.setStore(getStore());
			sg.setBarCode(barCode);
			Searching si = new Searching();
			si.setPageSize(10);
			if (barCode.length() == 13) {
				long codeNum = Long.parseLong(barCode);
				if (codeNum > 2e12 && codeNum < 29e11) {
					barCode = barCode.substring(2, 7);// 打秤类
					sg.setBarCode(barCode);
				}
				page = storeGoodsService.list(sg, si);
			} else {
				page = storeGoodsService.listByBarCodeLike(sg, si);
			}
			jsonResult.setResult(page);
			jsonResult.setOk();
		} catch (Exception e) {
			error(log, e, "按编码查找商品异常");
			jsonResult.setErrorMessage("添加失败，请联系管理员");
		}
		return jsonResult;
	}
	
}
